/*
 * CTCPClient.cpp
 *
 *  Created on: 05.03.2012
 *      Author: caffeine
 */
#include "CTCPClient.h"
#include <stdio.h>
#include <lampe/exception/Base.h>

//#include <StringUtils.h>

namespace lampe{
namespace network{

CTCPClient::CTCPClient(IClientCallback*callBack):CClient(callBack){
	sock=0;
}

bool CTCPClient::onStart(){
	bool res=isConnected();
	if (res){
		reader=new lampe::stream::tcp::CTCPReader(sock,true);
		writer=new lampe::stream::tcp::CTCPWriter(sock,true);
		onConnected();
	}
	return res;
}

void CTCPClient::onStop(){
	onDisconnected();
	clearSocket();
}

void CTCPClient::clearSocket(){
	if (reader!=0)
		reader->drop();
	if (writer!=0)
		writer->drop();
	reader=0;
	writer=0;
	do_close_socket(sock);
}

void CTCPClient::setConnect(void*data){
	SOCKET*s=(SOCKET*)data;
	sock=*s;
	CThread::start();
}

bool CTCPClient::isConnected(){
	return sock!=0;
}

bool CTCPClient::connectTo(String host,u32 port){
	if (isConnected())
		return false;
	loadNetworkLib();
	sock=create_socket();
	if (sock<0){
		GEN_ERROR("Socket initializing failed");
	}
	SOCK_ADDRESS addr=create_address();
	set_port(addr,(int)port);
	set_host(addr,host.c_str());
	if (!do_connect(sock,addr)){
		sock=0;
		GEN_ERROR(lampe::str::format("Can't connect to \"%s\":%u",host.c_str(),port));
	}
	CThread::start();
	return true;
}

lampe::stream::IReader*CTCPClient::getReader(){
	return reader;
}

lampe::stream::IWriter*CTCPClient::getWriter(){
	return writer;
}

void CTCPClient::Disconnect(){
	CThread::stop();
}

CTCPClient::~CTCPClient(){
	clearSocket();
	/*
	Disconnect();
	if (reader!=0)
		reader->drop();
	if (writer!=0)
		writer->drop();
		*/
}

extern ITCPClient*createTCPClient(IClientCallback*callBack){
	return new CTCPClient(callBack);
}


}//namespace network
}//namespace lampe
